package fh.app4stud.mensa;

import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.content.Context;
import android.content.res.Resources;
import fh.app4stud.mensa.data.LocationsSort;
import fh.app4stud.mensa.data.RestaurantLocation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: ivan plese
 * Date: 12.04.11
 * Time: 21:08
 * Version 1.0
 * To change this template use File | Settings | File Templates.
 */
public class MensaLocationService extends Service {


    ArrayList<RestaurantLocation>  restaurantLocations;
    private final String TAG = "MISC TAGS";


    private final IBinder locationServiceBinder = new LocalBinder();
    //TODO remove the string list implementation
    //ArrayList<String> locations = new ArrayList<String>();
    LocationManager lm;
    Location currentLocation;

    @Override
    public void onCreate() {
        Log.i(TAG, "Creating Service**********************************************");

        restaurantLocations = new ArrayList<RestaurantLocation>();


        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria crit = new Criteria();
        crit.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(crit, true);
        currentLocation = lm.getLastKnownLocation(provider);
    }

    public class LocalBinder extends Binder {
        MensaLocationService getService() {
            Log.i(TAG, "Returning ArrayLIst");
            return MensaLocationService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return locationServiceBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        try {

            String myFeed = getString(fh.app4stud.mensa.R.string.my_feed);
            URL url = new URL(myFeed);
             Log.i(TAG, "url opend");
            URLConnection connection = url.openConnection();

            int responseCode = -1;
            HttpURLConnection httpConnection = null;
            int iRetry = 0;

            while (iRetry < 10) {
                iRetry++;
                try {
                    httpConnection = (HttpURLConnection) connection;
                    httpConnection.setConnectTimeout(3000);
                    httpConnection.setDoInput(true);
                    httpConnection.connect();
                    responseCode = httpConnection.getResponseCode();
                } catch (IOException e) {
                    e.printStackTrace();
                    responseCode = -1;
                }
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    iRetry = 10;
                     Log.i(TAG, "If it came to here web service is working");
                    InputStream in = httpConnection.getInputStream();

                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

                    Document dom = documentBuilder.parse(in);
                    Element documentElement = dom.getDocumentElement();

                    //Clear old locations ... deprecated
                    //locations.clear();

                    //Get a list of each locations entry.
                    addAllLocations(documentElement);
                } else {
                    iRetry = 10;
                    //TODO create a dialog, ask if they want to chose the saved locations
                    Resources myResources = getResources();
                    InputStream inputStream = myResources.openRawResource(R.raw.locations);
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                    Document document = documentBuilder.parse(inputStream);
                    Element documentElement = document.getDocumentElement();
                    addAllLocations(documentElement);
                }
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } finally {
        }

        return Service.START_NOT_STICKY;
    }

    private void addAllLocations(Element documentElement) {
                 Log.i(TAG, "In addalllocations");
        NodeList nodeList = documentElement.getElementsByTagName("location");

        if (nodeList != null && nodeList.getLength() > 0) {

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element location = (Element) nodeList.item(i);
                Element city = (Element) location.getElementsByTagName("city").item(0);
                Element houseNumber = (Element) location.getElementsByTagName("houseNumber").item(0);
                Element locationName = (Element) location.getElementsByTagName("locationName").item(0);
                Element street = (Element) location.getElementsByTagName("street").item(0);
                Element zipCode = (Element) location.getElementsByTagName("zipCode").item(0);
                Element latitude = (Element) location.getElementsByTagName("latitude").item(0);
                Element longitude = (Element) location.getElementsByTagName("longitude").item(0);
                  Log.i(TAG, "getting the node values to str and doubles");
                String _city = city.getFirstChild().getNodeValue();
                String _houseNumber = houseNumber.getFirstChild().getNodeValue();
                String _locationName = locationName.getFirstChild().getNodeValue();
                String _streetName = street.getFirstChild().getNodeValue();
                String ZIPCode = zipCode.getFirstChild().getNodeValue();
                double _latitude = Double.parseDouble(latitude.getFirstChild().getNodeValue());
                double _longitude = Double.parseDouble(longitude.getFirstChild().getNodeValue());
                       Log.i(TAG, "creating the restLoc");
                //currentLocation.getLongitude(), currentLocation.getLatitude()
                RestaurantLocation restaurantLocation = new RestaurantLocation(_city, _houseNumber, _locationName, _streetName, ZIPCode, _longitude, _latitude, 1,1);
                 Log.i(TAG, "Passed the restaLoc creation");
                //addNewLocation(restaurantLocation);
                restaurantLocations.add(restaurantLocation);
                Log.i(TAG, "Added a location");
            }
        }
    }

    private void addNewLocation(RestaurantLocation location) {

        String locationDescription = location.getLocationName() + "\n"
                + location.getStreetName() + " " + location.getHouseNumber().toString() + "\n"
                + location.getCity();

        //add location to the location array
        //locations.add(locationDescription);
    }

    public ArrayList<RestaurantLocation> getRestaurantLocations(char sortBy) {

       /* switch (sortBy) {
            case 'c':
                Collections.sort(restaurantLocations, fh.app4stud.mensa.data.LocationsSort.CITY_ORDER);
                break;
            case 'd':
                Collections.sort(restaurantLocations, fh.app4stud.mensa.data.LocationsSort.DISTANCE_ORDER);
                break;
            default:
                Collections.sort(restaurantLocations, fh.app4stud.mensa.data.LocationsSort.CITY_ORDER);
        }*/

        return restaurantLocations;
    }
}
